const Controller = require('egg').Controller;

class BookController extends Controller {
  // 获取book页面
  async getBookList() {
    const bookList = await this.ctx.service.book.getBookList();
    const { ctx } = this;
    await ctx.render("/pc/book.html",{
        bookList
    })
  }
  // 后端操作

  // post添加操作
  async create() {
    try {
        const body = this.ctx.request.body;
        body.orderby = Number(body.orderby)  // 把orderby转换为数字格式
        await this.ctx.service.book.createBook(body)   // 传递获取到的body给服务层的book.js的createBook方法
        this.ctx.body = {
            code: 20000,
            message: true,
        }
    } catch (error) {
        this.ctx.body = {
            code: 30000,
            message: false,
        }
    }
}
// 查
async index() {
  try {
    //   const query = this.ctx.request.query;
      const bookList = await this.ctx.service.book.getBookList(); 
        console.log(bookList);
      this.ctx.body = {
          code: 20000,
          message: true,
          data: bookList,
      }
  } catch (error) {
      this.ctx.body = {
          code: 30000,
          message: false,
      }
  }
}

// 修改
async update() {
    try {
        const body = this.ctx.request.body;
        const id = this.ctx.params.id;
        await this.ctx.service.book.updateBook(id, body)
        this.ctx.body = {
            code: 20000,
            data: true
        }
    } catch (error) {
        this.ctx.body = {
            code: 30000,
            message: false
        }
    }
}
    // 删除
async destroy(){
    try{
        let id = this.ctx.params.id;
        await this.ctx.service.book.deleteBook(id)
        this.ctx.body = {
            code:20000,
            data:true
        } 
    }catch(error){
        this.ctx.body = {
            code:30000,
            message:false
        }
        
    }
  }

  async getBookDetail(){
    let id = this.ctx.params.id;
    // await console.log("我是获取到的id",id);
    const bookdetail = await this.ctx.service.book.getBookDetail(id)
    await console.log("我是controller处的book",bookdetail);
    await this.ctx.render("/pc/book_detail.html",{bookdetail})
  }

}

module.exports = BookController;
